<?php

namespace App\Utils;
use App\Models\Card;
use App\Models\City;
use App\Models\Company;
use App\Models\CompanyCity;
use App\Models\Error;
use App\Models\Goods;
use App\Models\GoodsTZL;
use App\Models\Order;
use App\Models\Shop;
use GuzzleHttp\Client;
use phpDocumentor\Reflection\Types\Boolean;

class TianZhenLan
{
    static $error = '';
    /**
     * @description 获取城市列表
     * @param $product
     * @return null
     */
    static function get_goods_cities($product) {
        $product = (string)$product;
        $url = "/open/service_area/query/list";
        $data = ["product_code" => $product];
        return self::send($url, $data);
    }


    /**
     * 获取产品列表 本接口用于将数据拉取来缓存在数据库中
     * @return bool
     */
    static function get_products() {
        $url = '/open/product/query/list';
        $data = [];
        $goods = self::send($url, $data);

        foreach($goods->items as $g) {

            $goods = GoodsTZL::where('product_code', $g->product_code)->first();
            $g = json_decode(json_encode($g), true);
            if ($goods) {
                $goods->update($g);
            } else {
                GoodsTZL::create($g);
            }
        }
        return true;
    }

    static function get_shops() {
        $url = "/open/store/query/list";
        $data = [];
        $shops = self::send($url, $data);
        $shops = $shops->items;
        $regions = [];
        $types  = [];

        foreach ($shops as $shop) {

            $regionName = $shop->district_name;
            if (!isset($regions[$regionName])) {
                 $region = City::where('city_name', 'like', $shop->city_name."%")
                    ->where('region_name', 'like', $regionName."%" )
                    ->first();
                 if (!$region) {
                     echo $regionName.'没有找到';
                     return;
                 }
                $regions[$regionName] = $region;
            }
            $region = $regions[$regionName];

            $cityName = $shop->city_name;
            // 找到城市类型
            if (!isset($types[$cityName])) {
                $comCity = CompanyCity::where('company', Company::TZL)->where('city_id', $region->city_id)->first();
                if ($comCity) {
                    $types[$cityName] = $comCity->type;
                } else {
                    echo '没有找到城市类型：'.$cityName;
                    echo "\n";
                }
            }

            // 录入城市列表
            $newShop = [
                'company'   => Company::TZL,
                'shop_code' => $shop->store_code,
                'name'      => $shop->name,
                'type'      => $types[$cityName],
                'city'      => $region->city_id,
                'region'    => $region->region_id,
                'region_name'=> $region->region_name,
                'address'   => $shop->short_addr,
                'tel'       => $shop->tel
            ];

            // 检查门店是否存在
            $oldShop = Shop::where(['company' => $newShop['company'], 'shop_code' => $newShop['shop_code']])->first();

            // 录入门店
            if ($oldShop) {
                $oldShop->update($newShop);
            } else {
                Shop::create($newShop);
            }
        }
        return true;
    }

    static function get_shop_time($shop, $product, $date, $isNew = true) {
        $url = '/open/schedule/query/batch/remaincountbytime';
        $data = [
            'biz_type'      => $isNew ? 'book' :  'modify_book_datetime',
            'store_code'    => (string)$shop,
            'product_code'  => (string)$product,
            'bookdate'      => $date,
            'days'          => "1"
        ];

        $res = self::send($url, $data);
        if ($res) {
            $times = $res->items;
            foreach ($times as $key => $time) {
                $times[$key] = ['time' => $time->time, 'valid' => $time->remain_count ? 1: 0];
            }
            return $times;
        } else {
            return [];
        }
    }

    /**
     * 创建拍摄订单,本接口无法立即获得预定是否成功，成功后会通过回调来进行通知
     * @param $orderId
     */
    static function create_order($orderId) {
        $order  = Order::find($orderId);
        $shop   = Shop::find($order->shop);
        $goods  = Goods::find($order->goods);
        // $card   = self::get_card($order->company_card);
        // $card = Card::where('')-
        $card = TianZhenLan::get_card($order->company_card);
        $data = [
            "app_order_sn"  => $order->sn_for_company,
            "store_code"    => $shop->shop_code,
            "product_code"  => (string)$goods->gid,
            "book_datetime" => self::format_datetime($order->time),
            "member_name"   => $order->user_name,
            "member_mobile" => $order->mobile,
            "p_member_name" => $order->photoer_name?: $order->user_name,   // 拍摄人
            "mobile"        => $order->photoer_mobile?: $order->mobile,  // 拍摄人联系方式
            "payment_detail"=> json_encode([[
                'trade_type'    => "1",
                'amount'        => $card->amount,
                'receipt'       => $order->company_card
            ]])
            // "email" => "15862135269@126.com",
            // "location" => "113.93885,22.514929",
            // "remark" => "我是备注"
        ];

        $url = "/open/book/startbook";
        return self::send($url, $data) !== null;
    }

    /**
     * 获取订单详情
     * @param $snForCompany
     * @return null
     */
    static function get_order_detail($snForCompany) {
        $data   = ['app_order_sn' => $snForCompany];
        $url    = "/open/book/query/detail";
        return self::send($url, $data);
    }

    /**
     * 时间格式化
     * @param $datetime
     * @return false|string
     */
    private static function format_datetime($datetime) {
        return substr($datetime, 0, 16);
    }

    /**
     * 修改时间
     * @param $orderSn
     * @param $time
     * @return bool
     */
    private static function update_time($snForCompany, $time) {
        $url = "/open/book/modifybooktime";
        $data = [
            'app_order_sn' => $snForCompany,
            'book_datetime' => self::format_datetime($time)
        ];
        $res = self::send($url, $data);
        return $res !== null;
    }

    /**
     * 修改账户信息
     * @param $orderSn
     * @param $name
     * @param $mobile
     * @return bool
     */
    private static function update_user($orderSn, $name, $mobile) {
        $url = "/open/book/update";
        $data = [
            'app_order_sn'   => $orderSn,
            'p_member_name' => $name,
            'mobile' => $mobile,
        ];
        $res = self::send($url, $data);
        return $res !== null;
    }

    /**
     * 修改订单
     * @param $orderSn
     * @param $oldShop
     * @param $newShop
     * @param $oldTime
     * @param $newTime
     * @param $oldName
     * @param $newName
     * @param $oldMobile
     * @param $newMobile
     */
    static function update_order($orderId, $oldShop, $newShop, $oldTime, $newTime, $oldName, $newName, $oldMobile, $newMobile) {

        $order = Order::find($orderId);
        $snForCompany = $order->sn_for_company;
        // 订单在24小时之类时，无法修改
        if (strtotime($oldTime) - time() < (24 * 060 * 60)) {
            self::$error = '24小时之类无法修改';
            return false;
        }

        if ($newShop != $oldShop) {
            // 门店改变了，则需要将之前订单取消，再次重新预定
            // 1.取消订单
            $res = self::cancel_order($orderId);
            if (!$res) {
                self::$error = "取消订单失败";
                return false;
            }

            // 等待订单同步成功 最大等待10秒
            for($i=0;$i<10;$i++) {
                sleep(1);
                $info = Order::find($orderId);
                if (!$info->company_sn) {   // 取消后会把改字段置空
                    break;
                }
                if ($i==9) {
                    self::$error = "取消订单失败";
                    return false;
                }
            }
            return self::create_order($orderId);
        } else {
            // 2.修改时间
            if ($newTime != $oldTime) {

                return self::update_time($snForCompany, $newTime);
            }

            // 3.修改账户信息
            if ($oldName != $newName || $oldMobile != $newMobile) {
                return self::update_user($snForCompany, $newName, $newMobile);
            }
        }
    }

    /**
     * 取消订单
     * @param $orderId
     * @return bool
     */
    static function cancel_order($orderId) {
        $order = Order::find($orderId);
        $url = "/open/book/cancelbook";
        $data = [
            'app_order_sn'  => $order->sn_for_company
        ];
        $res = self::send($url, $data);
        return $res !== null;
    }

    static function reset_order($orderId) {
        self::cancel_order($orderId);
        $order = Order::find($orderId);
        $order->photoer_name = '';
        $order->photoer_mobile = '';
        $order->shop = 0;
        $order->time = null;
        $order->note = '';
        $order->user_name = '';
        $order->save();
    }
    /**
     * 检查卡券信息
     * @param $card
     * @param $store
     * @param $product_code
     * @param $book_datetime
     * @param $mobile
     * @return bool
     */
    static function get_card($card, $store = null, $product_code = '', $book_datetime = null, $mobile = null) {
        // $store, $product_code, $book_datetime, $mobile
        $url = "/open/voucher/prepare";
        $data = [
            "voucher_code"  => $card,
            "store_code"    => $store, // 门店编号
            "product_code"  => (string)$product_code, // 产品编号
            "book_datetime" => $book_datetime, // 预定时间
            "mobile"        => $mobile  // 查询手机号
        ];
        $data = array_filter($data);
        return self::send($url, $data);
    }


    /*=========================================================*/
    /*======================= 接 口 结 束 ======================*/
    /*=========================================================*/
    private static function url($url) {
        return config('tzl.host') . $url;
    }

    private static function sign($data) {
        $app_key    = config('tzl.appkey');
        $app_secret = config('tzl.secret');
        $data['app_key'] = $app_key;

        // 排序
        ksort($data);

        $strArr = [];
        foreach($data as $key => $v) {
            array_push($strArr, $key.'='.$v.'&');
        }

        $data = implode( '', $strArr);
        $data = trim($data, "&");
        $sign = $app_secret.$data.$app_secret;
        $sign = md5($sign);
        return strtoupper($sign);
    }


    private static function send($url, $data) {
        $data = array_filter($data);
        $url = self::url($url);
        $data['app_key'] = config('tzl.appkey');
        $data['timestamp'] = datetime();
        $data['format'] = 'json';
        $data['v']  = "1";
        $data['sign_method'] = "MD5";
        $data['sign'] = self::sign($data);

        $client = new Client();
        $res = $client->post($url, ['json' => $data,  'headers' => ['Content-Type' => 'application/json']]);
        $body = json_decode($res->getBody());

        if ($body->code == 0) {
            Error::log('天真蓝接口成功:'.$url, $data, $body);
            return $body->data;
        } else {
            self::$error = $body->msg;
            Error::log('天真蓝请求报错:'.$url, $data, $body);
            return null;
        }
    }
}
